package com.appbee.gdata.youtube.client.presenter;

import javax.inject.Inject;

import com.appbee.core.client.jsni.JsArrayConverter;
import com.appbee.gdata.youtube.client.search.Feed;
import com.appbee.gdata.youtube.client.search.FeedCallback;
import com.appbee.gdata.youtube.client.search.FeedResult;
import com.appbee.gdata.youtube.client.search.YoutubeFilter;
import com.appbee.gdata.youtube.client.search.YoutubeService;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.SuggestOracle;

public class EntrySuggestOracle extends SuggestOracle
{
	private YoutubeService service;

	@Inject
	public EntrySuggestOracle(YoutubeService service)
	{
		this.service = service;
	}

	@Override
	public void requestSuggestions(final Request request, final Callback callback)
	{
		YoutubeFilter filter = new YoutubeFilter();
		filter.setQuery(request.getQuery());
		service.findByFilter(filter, new FeedCallback()
		{
			
			@Override
			public void onSuccess(FeedResult feedResult)
			{
				Feed feed = feedResult.getFeed();
				Response response = new Response();
				response.setMoreSuggestionsCount(feed.getOpenSearchTotalResults());
				response.setSuggestions(JsArrayConverter.toList(feed.getEntry()));
				callback.onSuggestionsReady(request, response);
			}
			
			@Override
			public void onFailure(Throwable caught)
			{
				Window.alert(caught.getMessage());

			}
		});
		
	}

}
